/**
 * IndexedDB基础模块
 * 提供数据库通用操作和抽象类定义
 */

// 数据库配置
export const DB_NAME = 'chatDb';
export const DB_VERSION = 1;

// 存储对象配置接口
export interface StorageConfig {
    storageName: string;
}

/**
 * 数据库管理器基础类
 * 提供数据库连接和通用操作
 */
export class DBManager {
    private db: IDBDatabase | null = null;
    private dbName: string;
    private dbVersion: number;

    constructor(dbName: string = DB_NAME, dbVersion: number = DB_VERSION) {
        this.dbName = dbName;
        this.dbVersion = dbVersion;
    }

    /**
     * 初始化数据库连接
     */
    async initDB(): Promise<boolean> {
        return new Promise((resolve, reject) => {
            if (this.db) {
                resolve(true);
                return;
            }

            const request = indexedDB.open(this.dbName, this.dbVersion);

            request.onerror = (event) => {
                console.error('数据库打开失败:', event);
                reject(false);
            };

            request.onsuccess = (event) => {
                this.db = (event.target as IDBOpenDBRequest).result;
                console.log('数据库连接成功');
                resolve(true);
            };

            request.onupgradeneeded = (event) => {
                const db = (event.target as IDBOpenDBRequest).result;
                this.createObjectStores(db);
            };
        });
    }

    /**
     * 创建存储对象
     * 由子类实现
     */
    protected createObjectStores(db: IDBDatabase): void {
        // 这是一个抽象方法，需要被子类覆盖实现
    }

    /**
     * 关闭数据库连接
     */
    closeDB() {
        if (this.db) {
            this.db.close();
            this.db = null;
            console.log('数据库连接已关闭');
        }
    }

    /**
     * 获取数据库对象
     */
    protected getDB(): IDBDatabase {
        if (!this.db) {
            throw new Error('数据库未初始化');
        }
        return this.db;
    }

    /**
     * 执行数据库事务操作
     * @param storeName 存储对象名称
     * @param mode 事务模式
     * @param callback 回调函数
     */
    protected async executeTransaction<T>(
        storeName: string,
        mode: IDBTransactionMode,
        callback: (store: IDBObjectStore) => IDBRequest<T>
    ): Promise<T> {
        await this.initDB();
        return new Promise((resolve, reject) => {
            try {
                const db = this.getDB();
                const transaction = db.transaction([storeName], mode);
                const store = transaction.objectStore(storeName);
                const request = callback(store);

                request.onsuccess = () => {
                    resolve(request.result);
                };

                request.onerror = (event) => {
                    console.error(`数据库操作失败: ${storeName}`, event);
                    reject(event);
                };
            } catch (error) {
                reject(error);
            }
        });
    }
}

/**
 * 抽象存储对象管理类
 * 定义通用的CRUD操作接口
 */
export abstract class BaseStorage<T> {
    protected dbManager: DBManager;
    protected abstract storageConfig: StorageConfig;

    constructor(dbManager: DBManager) {
        this.dbManager = dbManager;
    }

    /**
     * 添加记录
     */
    abstract add(data: T): Promise<boolean>;

    /**
     * 更新记录
     */
    abstract update(data: T): Promise<boolean>;

    /**
     * 删除记录
     */
    abstract delete(id: string | number): Promise<boolean>;

    /**
     * 获取单条记录
     */
    abstract get(id: string | number): Promise<T | null>;

    /**
     * 获取所有记录
     */
    abstract getAll(): Promise<T[]>;
}

// 数据库初始化事件监听器类型
export type DBStoreInitializer = (db: IDBDatabase) => void; 